import { resolve, dirname } from 'path';
import { fileURLToPath } from 'url';
import typescript from '@rollup/plugin-typescript';
import { nodeResolve } from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import babel from '@rollup/plugin-babel';
import dts from 'rollup-plugin-dts';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

const packageDir = resolve(__dirname, 'packages');
const componentsDir = resolve(packageDir, 'components');

// 获取组件包的配置
function createComponentConfig() {
  return [
    // ES Module 和 CommonJS 构建
    {
      input: resolve(componentsDir, 'src/index.ts'),
      external: ['react', 'react-dom', 'prop-types'],
      output: [
        {
          file: resolve(componentsDir, 'dist/index.esm.js'),
          format: 'esm',
          sourcemap: true,
        },
        {
          file: resolve(componentsDir, 'dist/index.cjs.js'),
          format: 'cjs',
          sourcemap: true,
          exports: 'named',
        },
      ],
      plugins: [
        nodeResolve({
          extensions: ['.js', '.jsx', '.ts', '.tsx'],
        }),
        commonjs(),
        typescript({
          tsconfig: resolve(componentsDir, 'tsconfig.json'),
          declaration: false,
          declarationMap: false,
        }),
        babel({
          babelHelpers: 'bundled',
          exclude: 'node_modules/**',
          extensions: ['.js', '.jsx', '.ts', '.tsx'],
          presets: [
            '@babel/preset-env',
            '@babel/preset-react',
            '@babel/preset-typescript',
          ],
        }),
      ],
    },
    // 类型声明文件构建
    {
      input: resolve(componentsDir, 'src/index.ts'),
      external: ['react', 'react-dom', 'prop-types'],
      output: {
        file: resolve(componentsDir, 'dist/index.d.ts'),
        format: 'esm',
      },
      plugins: [dts()],
    },
  ];
}

export default createComponentConfig();
